## chat_history.py

from typing import List, Dict, Any
from elasticsearch_client import ElasticsearchClient
import logging
from config import ELASTICSEARCH_CHAT_HISTORY_INDEX


class ChatHistory:
    def __init__(self, es_client: ElasticsearchClient):
        """Initialize the ChatHistory with an ElasticsearchClient instance.

        Args:
            es_client: The ElasticsearchClient instance to interact with Elasticsearch.
        """
        self.es_client = es_client

    def save_interaction(self, user_id: str, bot_id: str, message: str, response: str, conversation_id: str, tags: List[str]) -> bool:
        """Save an interaction to the chat history.

        Args:
            user_id: The ID of the user.
            bot_id: The ID of the bot.
            message: The message from the user.
            response: The response from the bot.
            conversation_id: The ID of the conversation.
            tags: A list of tags associated with the interaction.

        Returns:
            True if the interaction was saved successfully, False otherwise.
        """
        # Construct the document to save in Elasticsearch
        document = {
            "user_id": user_id,
            "bot_id": bot_id,
            "message": message,
            "response": response,
            "conversation_id": conversation_id,
            "tags": tags
        }
        try:
            # Save the document to the Elasticsearch index
            self.es_client.es.index(index=ELASTICSEARCH_CHAT_HISTORY_INDEX, body=document)
            return True
        except Exception as e:
            logging.error(f"Error saving interaction: {e}")
            return False

    def fetch_history(self, conversation_id: str) -> List[Dict[str, Any]]:
        """Fetch the chat history for a given conversation ID.

        Args:
            conversation_id: The ID of the conversation to fetch history for.

        Returns:
            A list of dictionaries containing the chat history. If no history is found, returns an empty list.
        """
        # Construct the Elasticsearch query
        es_query = {
            "query": {
                "match": {
                    "conversation_id": conversation_id
                }
            }
        }
        # Query the Elasticsearch index
        results = self.es_client.query_index(ELASTICSEARCH_CHAT_HISTORY_INDEX, es_query)
        if not results:
            logging.info(f"No chat history found for conversation ID: {conversation_id}")
        return results
